package com.example.script.admin.service.impl;

import com.example.script.admin.enums.AdminResult;
import com.example.script.admin.enums.ChooseScriptResult;
import com.example.script.admin.model.dto.AdminUserDto;
import com.example.script.admin.model.dto.ChooseScriptDto;
import com.example.script.admin.service.AdminUserService;
import com.example.script.admin.service.ProductService;
import com.example.script.mapper.AdminUserMapper;
import com.example.script.model.AdminUser;
import com.example.script.model.AdminUserExample;
import com.example.script.model.ChooseScript;
import com.example.script.security.util.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminUserServiceImpl implements AdminUserService {

    private static final Logger logger = LoggerFactory.getLogger(AdminUserServiceImpl.class);
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;
    @Autowired(required = false)
    private AuthenticationManager authenticationManager;
    @Autowired(required = false)
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private ProductService productService;


    @Override
    public AdminUser getAdminUserByUsername(String AdminUsername) {
        AdminUserExample example = new AdminUserExample();
        example.createCriteria().andAdminUsernameEqualTo(AdminUsername);
        List<AdminUser> users = adminUserMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    /**
     * 注册
     *
     * @param adminUserDto
     * @return
     */
    @Override
    public AdminResult register(AdminUserDto adminUserDto) {
        AdminUserExample userExample = new AdminUserExample();
        userExample.createCriteria().andAdminUsernameEqualTo(adminUserDto.getAdminUsername());
        if (adminUserMapper.countByExample(userExample) > 0) {
            return AdminResult.REGISTER_FAILED_USERNAME_SAME;
        }
        AdminUser user = new AdminUser();
        user.setAdminUsername(adminUserDto.getAdminUsername());
        user.setAdminPassword(passwordEncoder.encode(adminUserDto.getPassword()));
        if (adminUserMapper.insertSelective(user) > 0) {
            return AdminResult.REGISTER_SUCCESS;
        }
        return AdminResult.REGISTER_FAILED;
    }

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public Map<String, String> login(String username, String password) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(token);
        } catch (AuthenticationException e) {
            logger.error("用户名和密码错误" + e);
            return null;
        }
        //把authentication存到安全框架里面
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Map<String, String> tokenMap = new HashMap<>();
        if (authentication != null) {
            //从验证结果返回的authentication中获取UserDetails对象
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            //根据UserDetails对象生成token对象
            String tokenString = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", tokenString);
            tokenMap.put("tokenHead", jwtTokenUtil.getTokenHead());
            tokenMap.put("tokenHeader", jwtTokenUtil.getTokenHeader());

        }
        return tokenMap;
    }

    /**
     * 更新店家个人信息
     *
     * @param adminUserDto
     * @return
     */
    @Override
    public int updateAdminUser(AdminUserDto adminUserDto) {
        AdminUser adminUser = new AdminUser();
        adminUser.setAdminAddress(adminUserDto.getAddress());
        adminUser.setAdminPhone(adminUserDto.getPhone());
        adminUser.setAdminPassword(adminUserDto.getPassword());
        adminUser.setAdminStortName(adminUserDto.getAdminShortName());
        int result = 0;
        result = adminUserMapper.updateByPrimaryKey(adminUser);
        if (result <= 0) {
            return 0;
        }
        return result;
    }

    /**
     * 店家确认预约状态
     *
     * @param chooseScriptDto
     * @return
     */
    @Override
    public ChooseScriptResult chooseScript(ChooseScriptDto chooseScriptDto) {
        ChooseScript chooseScript = new ChooseScript();
        if (chooseScriptDto.getScriptId() != 0 && chooseScriptDto.getScriptId() != 1 && chooseScriptDto.getScriptId() != 2) {
            return ChooseScriptResult.CHOOSE_CODE_F;
        }
        chooseScript.setStateCode(chooseScriptDto.getScriptId());
        if (chooseScriptDto.getScriptId() == 0) {
            return ChooseScriptResult.CHOOSE_SCRIPT_ING;
        } else if (chooseScriptDto.getScriptId() == 1) {
            return ChooseScriptResult.CHOOSE_SCRIPT_SUCCESS;
        }
        return ChooseScriptResult.CHOOSE_SCRIPT_FAILED;
    }

    /**
     * 玩家发出预约申请
     * @param chooseScriptDto
     * @return
     */
    @Override
    public ChooseScriptResult userAppointment(ChooseScriptDto chooseScriptDto) {
        productService.findChooseByInvitationCode(chooseScriptDto.getInvitationCode()).size();

        return null;
    }
}
